<?php

/**
 * Entry AR
 * 
 * @author David Monllaó <david.monllao@gmail.com>
 */
class Entry extends ActiveRecordLang {

	/**
	 * Raw html to be cleaned
	 * @var string
	 */
    private $entrycode;
    
    /**
     * Entry labels
     * @var array
     */
    public $labels;

    
    public function __construct() {
    	parent::__construct();
        $this->tablename = 'entries';
    }

    
    /**
     * Extracts title, url, date, labels and content from the raw html
     * 
     * @param string $entrycode Raw html
     */
    public function getEntryData($entrycode) {

        $this->entrycode = $entrycode;
        
        $this->getTitle();
        $this->getDate();
        
        // Before the content clean
        $this->getLabels();
        
        $this->getCleanContent();
    }

    
    /**
     * Gets the entry title and url
     */
    public function getTitle() {

        preg_match("/<h3(.*?)>(.*?)<a[ ]*href=(.*?)[ ]*>(.*?)<\/a>(.*?)<\/h3>/", $this->entrycode, $entryhead);
        if (empty($entryhead[3]) || empty($entryhead[4])) {
            return false;
        }
        
        $this->dbobj->title = $entryhead[4];
        $this->dbobj->url = str_replace('"', '', str_replace("'", "", $entryhead[3]));
        
        if (strstr($this->dbobj->url, ' ') != false) {
            $this->dbobj->url = substr($this->dbobj->url, 0, strpos($this->dbobj->url, ' '));
        }
    }


    /**
     * Entry->date
     */
    public function getDate() {

        if (empty($this->dbobj->url)) {
            return false;
        }
        $url = $this->dbobj->url;

        $startpos = strpos($url, '/', 7) + 1;
        
        if (!$startpos || (strlen($url) < $startpos + 5)) {
        	return false;
        }
        
        $endpos = strpos($url, '/', $startpos + 5);
        $date = substr($url, $startpos, $endpos - $startpos);
        if (strlen($date) == 7) {
            $this->dbobj->date = $date;
        } else {
            return false;
        }
    }


    /**
     * Get the entry clean content (without html tags)
     */
    public function getCleanContent() {

        global $CONFIG;
        
        $this->entrycode = preg_replace("/\n/", " ", $this->entrycode);

        // Remove title
        $this->entrycode = preg_replace('<h3(.*?)h3>', '', $this->entrycode);
        $this->entrycode = str_replace('<>', '', $this->entrycode);
        
        // Remove footer
        $pattern = "/<div +class=['\"][a-zA-Z\-]*footer['\"] *>/";
        $contents = preg_split($pattern, $this->entrycode, -1, PREG_SPLIT_DELIM_CAPTURE);
        if (!empty($contents) && !empty($contents[0])) {
            $this->entrycode = rtrim($contents[0], '<');
        }

        // Maintain line breaks
        $brs = array('<br />', '<br>', '<br/>');
        $linebreakhash = '|||'.md5(rand(1000, 9999)).'|||';
        $showcode = str_replace($brs, $linebreakhash, $this->entrycode);
        $showcode = str_replace('</p>', $linebreakhash, $showcode);
        $showcode = str_replace('||%10||', $linebreakhash, $showcode);

        // Strip tags
        $showcode = strip_tags($showcode, $CONFIG->allowedtags);

        // Restore line breaks
        $showcode = str_replace($linebreakhash, '<br/>', $showcode);

        // And finally remove unnecessary line breaks
        $showcode = preg_replace("/<br\/> *(<br\/>| )+/", '<br/><br/>', $showcode);

        // Delete empty links
        $pattern = "/< *a(.*?)> *<\/a>/";
        $replace = "";
        $showcode = preg_replace($pattern, $replace, $showcode);
        
        // Clean <a> attributes
        // WARNING DIRTY HACK, adds a space to avoid problems with the next replace
        $pattern = "/< *a(.*?)href=(.*?)>(.*?)<\/a>/";
        $replace = '<a href=$2 >$3</a>';
        $showcode = preg_replace($pattern, $replace, $showcode);
    
        // Clean <a> attributes
        $pattern = "/< *a(.*?)href=(.*?) +(.*?)>(.*?)<\/a>/";
        $replace = '<a href=$2>$4</a>';
        $showcode = preg_replace($pattern, $replace, $showcode);
        
        $this->dbobj->contenttoshow = $showcode;
        
        return true;
    }


    /**
     * Obtains the entry labels
     */
    public function getLabels() {
        
        preg_match("#post-labels(.*?)>(.*?)<\/span>#", $this->entrycode, $labelsspan);
        if (!$labelsspan || ($labelsspan && empty($labelsspan[2]))) {
            $this->labels = false;
            return false;
        }
        
        preg_match_all("#<a href=(.*?)>(.*?)<#", $labelsspan[2], $labels);
        if (!$labels || ($labels && empty($labels[2]))) {
            $this->labels = false;
            return false;
        }

        // Replace to avoid problems with friendly urls
        $this->labels = str_replace('-', ' ', $labels[2]);
    }
    
    
    /**
     * Stores the entry labels into DB
     *
     * @param array $bloglabels An array to reduce the DB queries
     */
    public function saveLabels(&$bloglabels) {
        
        if (!$this->labels) {
            return false;
        }
        
        $obj->entryid = $this->dbobj->id;
        
        foreach ($this->labels as $label) {
            $obj->labelid = encode_text($label);
            $this->dbcnx->insertObject('entrylabels', $obj);
        }
    }
    
}
